package org.example.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.example.pojo.NutritionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class ApiUtils {
    @Value("${coze.token}")
    private String AUTH_TOKEN;

    private static final String BASE_URL = "https://api.coze.cn";
    private static OkHttpClient client;
    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS) // 连接超时时间
                .readTimeout(10, TimeUnit.SECONDS) // 读取超时时间
                .writeTimeout(10, TimeUnit.SECONDS) // 写入超时时间
                .build();
    }
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 方法1：上传图片到Coze，只返回id
    public String uploadImage(String imagePath) throws IOException {
        File file = new File(imagePath);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("image/*"), file))
                .build();

        Request request = new Request.Builder()
                .url(BASE_URL + "/v1/files/upload")
                .header("Authorization", "Bearer " + AUTH_TOKEN)
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            JsonNode jsonNode = objectMapper.readTree(response.body().string());
            return jsonNode.path("data").path("id").asText();
        }
    }

    // 方法2：发起聊天请求，返回id和conversation_id的数组
    public String[] initiateChat(String fileId) throws IOException {
        String jsonBody = String.format("""
                {
                    "bot_id": "7475207191428038694",
                    "user_id": "1",
                    "additional_messages": [
                        {
                            "content": "[{\\"type\\":\\"image\\",\\"file_id\\":\\"%s\\"}]",
                            "content_type": "object_string",
                            "role": "user"
                        }
                    ],
                    "stream": false
                }""", fileId);

        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json"), jsonBody);

        Request request = new Request.Builder()
                .url(BASE_URL + "/v3/chat")
                .header("Authorization", "Bearer " + AUTH_TOKEN)
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            JsonNode jsonNode = objectMapper.readTree(response.body().string());
            return new String[]{
                jsonNode.path("data").path("id").asText(),
                jsonNode.path("data").path("conversation_id").asText()
            };
        }
    }

    // 方法3：获取聊天消息，只返回output
    public String getChatMessages(String chatId, String conversationId) throws IOException {
        Request request = new Request.Builder()
                .url(String.format("%s/v3/chat/message/list?conversation_id=%s&chat_id=%s",
                        BASE_URL, conversationId, chatId))
                .header("Authorization", "Bearer " + AUTH_TOKEN)
                .get()
                .build();

        try (Response response = client.newCall(request).execute()) {
            JsonNode jsonNode = objectMapper.readTree(response.body().string());
            String content = jsonNode.path("data").get(0).path("content").asText();
            JsonNode contentNode = objectMapper.readTree(content);
            return contentNode.path("output").asText();
        }
    }

    // 方法4：获取营养分析
    public NutritionInfo analyzeNutrition(String imageUrl) throws IOException {
        String jsonBody = String.format("""
                {
                    "parameters": {
                        "input": "%s"
                    },
                    "workflow_id": "7475217074065293353"
                }""", imageUrl);

        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json"), jsonBody);

        Request request = new Request.Builder()
                .url(BASE_URL + "/v1/workflow/run")
                .header("Authorization", "Bearer " + AUTH_TOKEN)
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            JsonNode jsonNode = objectMapper.readTree(response.body().string());
            JsonNode dataNode = jsonNode.get("data");
            JsonNode parsedDataNode = objectMapper.readTree(dataNode.asText());
            JsonNode outputArray = parsedDataNode.get("output").get(0);
            return objectMapper.treeToValue(outputArray, NutritionInfo.class);
        }
    }
}
